<template>
	<view class="select-supervisor">
		<navBar title="选择人员" @goBack="uni.navigateBack()"></navBar>
		<view class="search">
			<u-search @search="confirmSearch" @change="confirmSearch" v-model="searchForm.keyWord" placeholder="请输入关键字"
				:showAction="false" clearabled height="88upx" />
		</view>
		<scroll-view @scrolltolower="scrolltolower" scroll-y
			:style="{height: 'calc(100vh - ' + containerOutsideHeight + 'px)'}">
			<view style="height: 100%;" v-if="supervisorArray.length > 0">
				<u-checkbox-group v-model="selectedPeople" @change="checkboxChange">
					<view class="special-work-personnel-list">
						<view v-for="(item, index) in supervisorArray" :key="index" @click.stop="lookDetail(item.id)">
							<view class="list-item">
								<view style="display: flex; align-items: center;" class="wid-320">
									<view style="box-sizing: border-box; padding-right: 18upx;">
										{{item.name}} {{item.cicCardNo || ''}}
									</view>
								</view>
								<view style="margin-right: 40rpx;">
									<easy-select-vue ref="easySelect" size="mini" style="width: 100%;"
										:value="item.label" @selectOne="selectOne"
										:options="item.personJobTypeList"></easy-select-vue>
								</view>
								<u-checkbox shape="circle" :name="item.id" :disabled="item.disabled"
									activeBackgroundColor="#2979ff" class="checkbox"></u-checkbox>
							</view>
						</view>
					</view>
				</u-checkbox-group>
				<view class="footer-button">
					<view class="button-placeholder"></view>
					<view class="button-group">
						<view @click="clickConfirmBtn" :loading="isLoading" class="button-primary">确定</view>
					</view>
				</view>
			</view>
			<u-empty v-else mode="data" text="數據爲空" icon="http://cdn.uviewui.com/uview/empty/data.png"></u-empty>
		</scroll-view>
	</view>
</template>

<script>
	import { mapGetters } from "vuex";
	import { getSystemHeightInfo } from "@/utils/common.js";
	import { getSafetySupervisorList } from "@/api/engineeringMaintenance/engineeringMaintenance.js";
	import { standardDataList, personGetListByOrgId } from "@/api/comprehensive/comprehensive.js";
	import { personCertificate_list } from "@/api/HongKong/hkAttendanceSheet.js";
	import easySelectVue from "../components/easy-select.vue";
	import { handleFormatDate, compareDate } from "@/utils/date.js";
	export default {
		name: "select-supervisor",
		components: {
			easySelectVue,
		},

		data() {
			return {
				// 容器之外的高度
				containerOutsideHeight: 0,
				// 监管人员列表
				supervisorArray: [],
				// 分页器
				paging: {
					pageNum: 1,
					pageSize: 10,
					total: 0,
				},
				// 搜索表单
				searchForm: {
					keyWord: "",
				},
				// 是否正在加载中
				isLoading: false,
				// 标准数据id列表
				standardDataIds: [],
				selectedPeople: [],
			}
		},
		computed: {
			...mapGetters(['dictMap'])
		},
		async onLoad() {
			this.initContainerData();
			await this.getStandardList();
			this.supervisorArray = await this.getSafetySupervisorArray();
			// console.log(this.supervisorArray, 'renyuanliebiao1')
			const eventChannel = this.getOpenerEventChannel();
			eventChannel.on('sendPerson', (item) => {
				console.log(item.data, 'sendPerson')
				for (const i of this.supervisorArray) {
					for (let k of item.data) {
						if (i.id === k.id) {
							i.label = k.label
						}
					}
				}
				this.selectedPeople = item.data.map(it => it.id)

				console.debug(this.supervisorArray)
			})
			this.eventChannel = eventChannel
		},
		methods: {
			selectChange(val) {
				console.log(val);
			},
			selectOne(options) {
				console.log(options)
				this.supervisorArray.forEach(it => {
					if (it.id === options.personId) {
						it.label = options.label
					}
				})
			},
			useOutClickSide() {
				this.$refs.easySelect.hideOptions && this.$refs.easySelect.hideOptions()
			},
			checkboxChange(e) {
				this.selectedPeople = e
			},
			/** 初始化容器数据 */
			initContainerData() {
				const {
					stateHeight,
					bottomHeight,
					navbarHeight
				} = getSystemHeightInfo();
				this.containerOutsideHeight = stateHeight + bottomHeight + navbarHeight + 90;
			},
			handleConfirm(val) {
				console.log(val, '--')
			},

			/** 获取标准数据 */
			getStandardList() {
				return new Promise(resolve => {
					standardDataList({
						currPage: 1,
						pageSize: 99999,
						params: {
							type: "engineering_structure",
							treeLevel: 1
						},
					}).then(res => {
						const {
							list
						} = res.result;

						this.standardDataIds = [list.filter(item => item.treeLevel === 1).find(item => item
							.code === (this.type == 1 ? "gcwb" : "zhzzdx")).id];
						resolve();
					});
				});
			},

			/** 获取人员列表信息 */
			getSafetySupervisorArray() {
				return new Promise(resolve => {
					const {
						pageNum,
						pageSize
					} = this.paging;
					let data = {};
					let typeIds = this.dictMap['person_type'].filter(item => ['zc', 'lwpq', 'rsdl'].includes(item
						.groupCode)).map(item => item.id).join(',')
					let resq = {
						currPage: pageNum,
						pageSize,
						params: {
							// orgId: this.orgId,
							// standardDataIds: this.personType === 'jkzb' ? undefined : this.standardDataIds,
							stationTypeIds: [102, 104],
							projectId: uni.getStorageSync('isOwner'),
							name: this.searchForm.keyWord,
							// personType: this.personType === 'jkzb' ? 'employee_type_manager' : undefined,
							...data,
						},
					}
					personGetListByOrgId(resq).then(async res => {
						const { list, total } = res.result;
						// console.log(res.result.currentDate)
						for (const item of list) {
							item.label = ''
							item.disabled = false
							if (!item.personnelCallList || item.personnelCallList.length === 0) {
								item.disabled = true
							}
							if (item.personnelCallList && item.personnelCallList.length) {
								let index = 0
								for (let i = 0; i < item.personnelCallList.length; i++) {
									const effectiveDate = new Date(`${handleFormatDate(new Date(item.personnelCallList[i].effectiveDate))} 23:59:59`).getTime()
									if (item.personnelCallList[i].certificateCategoryCode !== 'certificate_category_rsi' || (effectiveDate < item.currentDate)) {
										index++
									}
								}
								if (index === item.personnelCallList.length) {
									item.disabled = true
								}
							}
							if (item.personJobTypeList && item.personJobTypeList.length) {
								item.personJobTypeList = item.personJobTypeList.map((it, index) => ({
									...it,
									value: it.personId,
									label: this.getName(this.$store.getters.dictMap[
										'gwgz'],this.$store.getters.dictMap[
										'gwgz_special_jobs'], it.code)
								}))
							} else {
								item.jobTypeCodes = []
							}
						}
						this.paging.total = total;
						console.log(list)
						resolve(list);
					});
				});
			},
			getName(arr,arr2, code) {
				arr = [...arr, ...arr2]
				let name = ''
				if (arr && arr.length > 0) {
					name = arr.find(it => it.code === code) ? arr.find(it => it.code === code).name : ''
				}
				return name
			},

			/** 容器滚动到底部 */
			async scrolltolower() {
				// 判断是否有下一页
				if (!this.isLoading && this.paging.pageNum * this.paging.pageSize < this.paging.total) {
					// 加载...
					this.isLoading = true;
					this.paging.pageNum++;
					this.supervisorArray = this.supervisorArray.concat(await this.getSafetySupervisorArray());
					this.isLoading = false;
				}
			},

			/** 点击确认按钮 */
			clickConfirmBtn() {
				uni.navigateBack({
					success: () => {
						this.eventChannel.emit("getPersonInfo", {
							data: this.supervisorArray.filter(it => this.selectedPeople.includes(it
								.id)) || []
						})
					}
				});
			},

			/** 确认搜索 */
			async confirmSearch() {
				this.paging.pageNum = 1;
				this.supervisorArray = await this.getSafetySupervisorArray();
			},
			lookDetail(id) {
				uni.navigateTo({
					url: `/subpackage-enginner/pages/engineeringMaintenance/personnelAttendance/certificateDetails?id=${id}`,

				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.select-supervisor {
		font-size: 32upx;
		/* #ifdef MP-WEIXIN */
		padding-top: 200rpx;

		/* #endif */
		.search {
			padding: 42upx 36upx 14upx 28upx;
			position: sticky;
			top: 0px;
			border-top: 1px solid #fff;
			background: #fff;
			z-index: 1;
		}

		.u-checkbox-group {
			display: block;
		}

		.checkbox {
			::v-deep .uni-checkbox-input {
				border-radius: 50%;
			}
		}

		.select-supervisor-list {
			padding: 0 36upx 0 28upx;
			color: #445469;
			font-weight: 500;
			width: 100%;

			.list-item {

				padding: 40upx;
				border-bottom: 1px solid #e2e5ed;
				display: flex;
				align-items: center;
				justify-content: space-between;
			}

			::v-deep .u-radio-group {
				flex: initial;

				.u-radio__icon-wrap {
					margin-right: 0;
				}
			}
		}
	}

	.special-work-personnel-list {
		padding: 0 36upx 0 28upx;
		color: #445469;
		font-weight: 500;
		/* #ifdef MP-WEIXIN */
		width: 100%;
		/* #endif */
		.list-item {
			/* #ifdef APP-PLUS || H5 */
			padding: 40upx 18upx 34upx 28upx;
			/* #endif */
			/* #ifdef MP-WEIXIN */
			padding: 42upx 36upx 14upx 28upx;
			/* #endif */
			border-bottom: 1px solid #e2e5ed;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.wid-320 {
				/* #ifdef APP-PLUS || H5 */
				width: calc(100% - 44upx);
				/* #endif */

				/* #ifdef MP-WEIXIN */
				width: calc(100% - 44upx);
				/* #endif */
			}
		}

		::v-deep .u-radio-group {
			flex: initial;

			.u-radio__icon-wrap {
				margin-right: 0;
			}
		}
	}

	.footer-button {
		height: 154upx;

		.button-placeholder {
			height: 100%;
		}

		.button-group {
			height: 154upx;
			padding: 30upx;
			box-sizing: border-box;
			background: #fff;
			position: fixed;
			width: 100vw;
			bottom: 0;
			z-index: 1;

			.button-primary {
				background: #2f80ed;
				border-radius: 4upx;
				color: #fff;
				font-weight: bold;
				line-height: 92upx;
				text-align: center;
			}
		}
	}
</style>